/*
 * Copyright (c) 2019. Lorem ipsum dolor sit amet, consectetur adipiscing elit.
 * Morbi non lorem porttitor neque feugiat blandit. Ut vitae ipsum eget quam lacinia accumsan.
 * Etiam sed turpis ac ipsum condimentum fringilla. Maecenas magna.
 * Proin dapibus sapien vel ante. Aliquam erat volutpat. Pellentesque sagittis ligula eget metus.
 * Vestibulum commodo. Ut rhoncus gravida arcu.
 */

package com.yawn.nio.server;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;
import java.util.Iterator;
import java.util.Scanner;
import java.util.Set;

public class NioClient {

    public static void main(String[] args) throws IOException {
        InetSocketAddress serverAddress = new InetSocketAddress("localhost", 8000);
        Selector selector = Selector.open();
        /// 两种方式获取socketChannel
//        SocketChannel socketChannel = SocketChannel.open(serverAddress);
        SocketChannel socketChannel = SocketChannel.open();
        socketChannel.configureBlocking(false);
        boolean connect = socketChannel.connect(serverAddress);
//        if (!connect) {
//            // 连接失败
//            socketChannel.register(selector, SelectionKey.OP_CONNECT);
//        }
        socketChannel.register(selector, SelectionKey.OP_READ);

        new Thread(() -> handleMsg(selector)).start();

        Scanner scanner = new Scanner(System.in);
        while (scanner.hasNextLine()) {
            String msg = scanner.nextLine();
            if (msg != null && msg.length() > 0) {
                socketChannel.write(
                        Charset.forName("UTF-8")
                                .encode(msg));
                socketChannel.register(selector, SelectionKey.OP_READ);
            }
        }
    }

    private static void handleMsg(Selector selector) {
        while (true) {
            try {
                int readyChannels = selector.select();
//                System.out.println("selector获取到" + readyChannels + "个channel");
                if (readyChannels == 0) continue;
                Set<SelectionKey> selectionKeys = selector.selectedKeys();
                Iterator<SelectionKey> iterator = selectionKeys.iterator();
                while (iterator.hasNext()) {
                    SelectionKey selectionKey = iterator.next();
                    iterator.remove();
                    if (selectionKey.isReadable()) {
                        SocketChannel socketChannel = (SocketChannel) selectionKey.channel();
                        socketChannel.configureBlocking(false);
                        ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
                        socketChannel.read(byteBuffer);
                        byteBuffer.flip();
                        System.out.println(Charset.defaultCharset().decode(byteBuffer));
                        socketChannel.register(selector, SelectionKey.OP_WRITE);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
